import React, { useState } from 'react';
import {
  useQuery,
  useMutation,
  useQueryClient,
  useInfiniteQuery,
} from '@tanstack/react-query';
import './styles.css';

// API 基础 URL
const API_BASE = 'http://localhost:3009';

// API 函数
const api = {
  // 获取用户列表
  getUsers: async () => {
    const response = await fetch(`${API_BASE}/users`);
    if (!response.ok) throw new Error('获取用户列表失败');
    return response.json();
  },

  // 获取单个用户
  getUser: async (id) => {
    const response = await fetch(`${API_BASE}/users/${id}`);
    if (!response.ok) throw new Error('获取用户信息失败');
    return response.json();
  },

  // 创建用户
  createUser: async (userData) => {
    const response = await fetch(`${API_BASE}/users`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(userData),
    });
    if (!response.ok) throw new Error('创建用户失败');
    return response.json();
  },

  // 更新用户
  updateUser: async ({ id, ...userData }) => {
    const response = await fetch(`${API_BASE}/users/${id}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(userData),
    });
    if (!response.ok) throw new Error('更新用户失败');
    return response.json();
  },

  // 删除用户
  deleteUser: async (id) => {
    const response = await fetch(`${API_BASE}/users/${id}`, {
      method: 'DELETE',
    });
    if (!response.ok) throw new Error('删除用户失败');
    return response.json();
  },

  // 获取文章列表（分页）
  getPosts: async ({ pageParam = 1, limit = 2 }) => {
    const response = await fetch(
      `${API_BASE}/posts?_page=${pageParam}&_limit=${limit}&_expand=user`
    );
    if (!response.ok) throw new Error('获取文章列表失败');
    const data = await response.json();
    return {
      data,
      nextPage: data.length === limit ? pageParam + 1 : undefined,
      hasNextPage: data.length === limit,
    };
  },

  // 搜索用户
  searchUsers: async (query) => {
    const response = await fetch(`${API_BASE}/users?q=${query}`);
    if (!response.ok) throw new Error('搜索用户失败');
    return response.json();
  },
};

// 用户列表组件
const UserList = () => {
  const queryClient = useQueryClient();
  const [selectedUserId, setSelectedUserId] = useState(null);
  const [editingUser, setEditingUser] = useState(null);
  const [newUser, setNewUser] = useState({ name: '', email: '', age: '', city: '' });
  const [searchQuery, setSearchQuery] = useState('');

  // 获取用户列表
  const {
    data: users = [],
    isLoading,
    error,
    refetch,
    isFetching,
  } = useQuery({
    queryKey: ['users'],
    queryFn: api.getUsers,
    staleTime: 5 * 60 * 1000, // 5分钟内数据被认为是新鲜的
    cacheTime: 10 * 60 * 1000, // 缓存10分钟
    refetchOnWindowFocus: false, // 窗口聚焦时不自动重新获取
  });

  // 获取单个用户详情
  const {
    data: selectedUser,
    isLoading: isLoadingUser,
  } = useQuery({
    queryKey: ['user', selectedUserId],
    queryFn: () => api.getUser(selectedUserId),
    enabled: !!selectedUserId, // 只有当 selectedUserId 存在时才执行查询
  });

  // 搜索用户
  const {
    data: searchResults = [],
    isLoading: isSearching,
  } = useQuery({
    queryKey: ['users', 'search', searchQuery],
    queryFn: () => api.searchUsers(searchQuery),
    enabled: searchQuery.length > 0,
    debounce: 300, // 防抖
  });

  // 创建用户 Mutation
  const createUserMutation = useMutation({
    mutationFn: api.createUser,
    onSuccess: () => {
      // 成功后刷新用户列表
      queryClient.invalidateQueries({ queryKey: ['users'] });
      setNewUser({ name: '', email: '', age: '', city: '' });
      alert('用户创建成功！');
    },
    onError: (error) => {
      alert(`创建失败: ${error.message}`);
    },
  });

  // 更新用户 Mutation
  const updateUserMutation = useMutation({
    mutationFn: api.updateUser,
    onSuccess: (updatedUser) => {
      // 乐观更新：立即更新缓存
      queryClient.setQueryData(['users'], (oldUsers) =>
        oldUsers.map((user) =>
          user.id === updatedUser.id ? updatedUser : user
        )
      );
      // 同时更新单个用户的缓存
      queryClient.setQueryData(['user', updatedUser.id], updatedUser);
      setEditingUser(null);
      alert('用户更新成功！');
    },
    onError: (error) => {
      alert(`更新失败: ${error.message}`);
    },
  });

  // 删除用户 Mutation
  const deleteUserMutation = useMutation({
    mutationFn: api.deleteUser,
    onSuccess: (_, deletedUserId) => {
      // 从缓存中移除用户
      queryClient.setQueryData(['users'], (oldUsers) =>
        oldUsers.filter((user) => user.id !== deletedUserId)
      );
      // 移除单个用户的缓存
      queryClient.removeQueries({ queryKey: ['user', deletedUserId] });
      if (selectedUserId === deletedUserId) {
        setSelectedUserId(null);
      }
      alert('用户删除成功！');
    },
    onError: (error) => {
      alert(`删除失败: ${error.message}`);
    },
  });

  const handleCreateUser = (e) => {
    e.preventDefault();
    if (!newUser.name || !newUser.email) {
      alert('请填写姓名和邮箱');
      return;
    }
    createUserMutation.mutate({
      ...newUser,
      age: parseInt(newUser.age) || 0,
      avatar: `https://api.dicebear.com/7.x/avataaars/svg?seed=${Date.now()}`,
    });
  };

  const handleUpdateUser = (e) => {
    e.preventDefault();
    updateUserMutation.mutate(editingUser);
  };

  const handleDeleteUser = (userId) => {
    if (window.confirm('确定要删除这个用户吗？')) {
      deleteUserMutation.mutate(userId);
    }
  };

  if (isLoading) return <div className="loading">加载用户列表中...</div>;
  if (error) return <div className="error">错误: {error.message}</div>;

  const displayUsers = searchQuery ? searchResults : users;

  return (
    <div className="user-section">
      <div className="section-header">
        <h2>用户管理 {isFetching && <span className="fetching">🔄</span>}</h2>
        <button onClick={refetch} disabled={isFetching}>
          刷新列表
        </button>
      </div>

      {/* 搜索框 */}
      <div className="search-box">
        <input
          type="text"
          placeholder="搜索用户..."
          value={searchQuery}
          onChange={(e) => setSearchQuery(e.target.value)}
        />
        {isSearching && <span className="searching">搜索中...</span>}
      </div>

      {/* 创建用户表单 */}
      <form onSubmit={handleCreateUser} className="create-form">
        <h3>创建新用户</h3>
        <div className="form-row">
          <input
            type="text"
            placeholder="姓名"
            value={newUser.name}
            onChange={(e) => setNewUser({ ...newUser, name: e.target.value })}
          />
          <input
            type="email"
            placeholder="邮箱"
            value={newUser.email}
            onChange={(e) => setNewUser({ ...newUser, email: e.target.value })}
          />
          <input
            type="number"
            placeholder="年龄"
            value={newUser.age}
            onChange={(e) => setNewUser({ ...newUser, age: e.target.value })}
          />
          <input
            type="text"
            placeholder="城市"
            value={newUser.city}
            onChange={(e) => setNewUser({ ...newUser, city: e.target.value })}
          />
          <button
            type="submit"
            disabled={createUserMutation.isPending}
          >
            {createUserMutation.isPending ? '创建中...' : '创建用户'}
          </button>
        </div>
      </form>

      {/* 用户列表 */}
      <div className="users-grid">
        {displayUsers.map((user) => (
          <div key={user.id} className="user-card">
            <img src={user.avatar} alt={user.name} className="avatar" />
            <div className="user-info">
              <h4>{user.name}</h4>
              <p>{user.email}</p>
              <p>年龄: {user.age} | 城市: {user.city}</p>
            </div>
            <div className="user-actions">
              <button onClick={() => setSelectedUserId(user.id)}>
                查看详情
              </button>
              <button onClick={() => setEditingUser({ ...user })}>
                编辑
              </button>
              <button
                onClick={() => handleDeleteUser(user.id)}
                disabled={deleteUserMutation.isPending}
                className="delete-btn"
              >
                删除
              </button>
            </div>
          </div>
        ))}
      </div>

      {/* 用户详情模态框 */}
      {selectedUserId && (
        <div className="modal">
          <div className="modal-content">
            <div className="modal-header">
              <h3>用户详情</h3>
              <button onClick={() => setSelectedUserId(null)}>×</button>
            </div>
            {isLoadingUser ? (
              <div className="loading">加载用户详情中...</div>
            ) : selectedUser ? (
              <div className="user-details">
                <img src={selectedUser.avatar} alt={selectedUser.name} className="large-avatar" />
                <h4>{selectedUser.name}</h4>
                <p><strong>邮箱:</strong> {selectedUser.email}</p>
                <p><strong>年龄:</strong> {selectedUser.age}</p>
                <p><strong>城市:</strong> {selectedUser.city}</p>
                <p><strong>ID:</strong> {selectedUser.id}</p>
              </div>
            ) : (
              <div className="error">用户不存在</div>
            )}
          </div>
        </div>
      )}

      {/* 编辑用户模态框 */}
      {editingUser && (
        <div className="modal">
          <div className="modal-content">
            <div className="modal-header">
              <h3>编辑用户</h3>
              <button onClick={() => setEditingUser(null)}>×</button>
            </div>
            <form onSubmit={handleUpdateUser} className="edit-form">
              <input
                type="text"
                placeholder="姓名"
                value={editingUser.name}
                onChange={(e) => setEditingUser({ ...editingUser, name: e.target.value })}
              />
              <input
                type="email"
                placeholder="邮箱"
                value={editingUser.email}
                onChange={(e) => setEditingUser({ ...editingUser, email: e.target.value })}
              />
              <input
                type="number"
                placeholder="年龄"
                value={editingUser.age}
                onChange={(e) => setEditingUser({ ...editingUser, age: parseInt(e.target.value) })}
              />
              <input
                type="text"
                placeholder="城市"
                value={editingUser.city}
                onChange={(e) => setEditingUser({ ...editingUser, city: e.target.value })}
              />
              <div className="form-actions">
                <button type="button" onClick={() => setEditingUser(null)}>
                  取消
                </button>
                <button
                  type="submit"
                  disabled={updateUserMutation.isPending}
                >
                  {updateUserMutation.isPending ? '更新中...' : '更新'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
};

// 无限滚动文章列表组件
const InfinitePostList = () => {
  const {
    data,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
    isLoading,
    error,
  } = useInfiniteQuery({
    queryKey: ['posts'],
    queryFn: api.getPosts,
    getNextPageParam: (lastPage) => lastPage.nextPage,
    staleTime: 2 * 60 * 1000,
  });

  if (isLoading) return <div className="loading">加载文章列表中...</div>;
  if (error) return <div className="error">错误: {error.message}</div>;

  const posts = data?.pages.flatMap(page => page.data) || [];

  return (
    <div className="posts-section">
      <h2>文章列表（无限滚动）</h2>
      <div className="posts-list">
        {posts.map((post) => (
          <div key={post.id} className="post-card">
            <h3>{post.title}</h3>
            <p className="post-content">{post.content}</p>
            <div className="post-meta">
              <span>作者: {post.user?.name || '未知'}</span>
              <span>点赞: {post.likes}</span>
              <span>发布时间: {new Date(post.createdAt).toLocaleDateString()}</span>
            </div>
          </div>
        ))}
      </div>
      
      {hasNextPage && (
        <button
          onClick={() => fetchNextPage()}
          disabled={isFetchingNextPage}
          className="load-more-btn"
        >
          {isFetchingNextPage ? '加载中...' : '加载更多'}
        </button>
      )}
      
      {!hasNextPage && posts.length > 0 && (
        <div className="no-more">没有更多文章了</div>
      )}
    </div>
  );
};

// 查询状态展示组件
const QueryStatus = () => {
  const queryClient = useQueryClient();
  const [queryKeys, setQueryKeys] = useState([]);

  React.useEffect(() => {
    const updateQueryKeys = () => {
      const cache = queryClient.getQueryCache();
      const queries = cache.getAll();
      setQueryKeys(queries.map(query => ({
        key: JSON.stringify(query.queryKey),
        state: query.state.status,
        dataUpdatedAt: query.state.dataUpdatedAt,
        isFetching: query.state.isFetching,
      })));
    };

    updateQueryKeys();
    const interval = setInterval(updateQueryKeys, 1000);
    return () => clearInterval(interval);
  }, [queryClient]);

  return (
    <div className="query-status">
      <h2>查询状态监控</h2>
      <div className="status-grid">
        {queryKeys.map((query, index) => (
          <div key={index} className={`status-item ${query.state}`}>
            <div className="query-key">{query.key}</div>
            <div className="query-state">
              状态: {query.state} {query.isFetching && '🔄'}
            </div>
            <div className="query-time">
              更新时间: {query.dataUpdatedAt ? new Date(query.dataUpdatedAt).toLocaleTimeString() : '未更新'}
            </div>
          </div>
        ))}
      </div>
      
      <div className="cache-actions">
        <button onClick={() => queryClient.invalidateQueries()}>
          刷新所有查询
        </button>
        <button onClick={() => queryClient.clear()}>
          清空缓存
        </button>
      </div>
    </div>
  );
};

// 主组件
const ReactQueryDemo = () => {
  const [activeTab, setActiveTab] = useState('users');

  return (
    <div className="react-query-demo">
      <header className="demo-header">
        <h1>🚀 React Query 完整示例</h1>
        <p>展示 TanStack Query 的各种功能：查询、变更、缓存、无限滚动等</p>
      </header>

      <nav className="demo-nav">
        <button
          className={activeTab === 'users' ? 'active' : ''}
          onClick={() => setActiveTab('users')}
        >
          用户管理
        </button>
        <button
          className={activeTab === 'posts' ? 'active' : ''}
          onClick={() => setActiveTab('posts')}
        >
          文章列表
        </button>
        <button
          className={activeTab === 'status' ? 'active' : ''}
          onClick={() => setActiveTab('status')}
        >
          查询状态
        </button>
      </nav>

      <main className="demo-content">
        {activeTab === 'users' && <UserList />}
        {activeTab === 'posts' && <InfinitePostList />}
        {activeTab === 'status' && <QueryStatus />}
      </main>

      <footer className="demo-footer">
        <p>💡 提示：打开 React Query DevTools 查看更多调试信息</p>
        <p>🔧 确保 JSON Server 运行在 http://localhost:3001</p>
      </footer>
    </div>
  );
};

export default ReactQueryDemo;